const TicketExports = require('../../../services/tickets-exports');

module.exports = function(app) {
    const router = app.router;

    const Type = app.models.Type;

    router.get('/ticket/export', function * () {
        const query = this.query;

        let startTime = +query.start_time || 0;
        let endTime = +query.end_time || 0;
        let ticketExport = {};

        const products = yield Type.where({
            deleted: 0
        })
        .fetchAll({
            withRelated: ['parent']
        });

        const types = JSON.parse(JSON.stringify(products));

        if(!startTime && !endTime) {
            ticketExport = new TicketExports(types);
        }
        else {
            ticketExport = new TicketExports(types, new Date(startTime * 1000), new Date(endTime * 1000));
        }

        yield ticketExport.total();

        this.set('Content-disposition', 'attachment;filename=' + encodeURI(ticketExport._excel._name) + '.xlsx');
        this.body = yield ticketExport._excel.export();
    });
};
